package com.example.caorl.job5thread.interrupt;

public class TestThread2 extends Thread {

    private boolean stop = false;

    public synchronized boolean isStop() {
        return stop;
    }

    public synchronized void stopThread() {
        setStop(true);
    }

    public synchronized void setStop(boolean stop) {
        this.stop = stop;
        //调用interrupt加快线程终止，避免一些长时间的阻塞
        this.interrupt();
    }

    public static void main(String[] args) throws Exception {
        TestThread2 thread = new TestThread2();

        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Interrupting thread...");
//        thread.interrupt();
        thread.setStop(true);
        Thread.sleep(1000);
        System.out.println("线程是否中断：" + thread.isInterrupted());
        Thread.sleep(3000);
        System.out.println("Stopping application...");
    }

    @Override
    public void run() {
        while (!stop) {
            System.out.println("My Thread is running...");
            // 让该循环持续一段时间，使上面的话打印次数少点
            /*long time = System.currentTimeMillis();
            while ((System.currentTimeMillis() - time < 1000)) {
            }
            if (Thread.currentThread().isInterrupted()) {
                return;
            }*/
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("My Thread exiting under request...");
    }
}
